//
//  RecommendViewController.m
//  AutoHome
//
//  Created by wqh on 15-5-9.
//  Copyright (c) 2015年 Wqh. All rights reserved.
//

#import "RecommendViewController.h"
#import "TopTabControlDefine.h"
#import "RecommendContent.h"
#import "NewestRecommend.h"
#import "NewsflashRecommend.h"
#import "BaseGrayView.h"
#import "MoreMenuScrollView.h"
#import "SelectMenuCell.h"
#import "NoSelectMenuCell.h"
#import "AppDelegate.h"

#define kMoreScrollViewHeight (350)
#define kSelectCellId @"CellId1"
#define kNoSelectCellId @"CellId2"

@interface RecommendViewController ()<TopTabControlDataSource,UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic) TopTabControl *tabControl;

@property (nonatomic,strong) NSMutableArray *recommendInfo;
@property (nonatomic) NSMutableArray *noRecomendInfo;

@property (nonatomic) UIButton *moreContentBtn;


@property (nonatomic) MoreMenuScrollView *moreMenuScrollView;
@property (nonatomic) BaseGrayView *bgGrayView;
@property (nonatomic) UIView *topView;
@property (nonatomic) UIView *bottomView;

@property (nonatomic) NSMutableArray *selectArr;
@property (nonatomic) NSMutableArray *noSelectArr;

@end

@implementation RecommendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.hidden = YES;
    self.navigationController.navigationBar.translucent = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
    
    
    self.selectArr = [NSMutableArray array];
    self.noSelectArr = [NSMutableArray array];
 
    
    NSString *isFirst = [[NSUserDefaults standardUserDefaults] objectForKey:@"firstLogin"];
    
    //判断是否是第一次登陆
    if (!isFirst) { //不存在 表示是第一次登陆
      
        NSString *recommendFilePath = [[NSBundle mainBundle] pathForResource:@"RecommendInfo" ofType:@"plist"];
        
        self.recommendInfo = [NSMutableArray arrayWithContentsOfFile:recommendFilePath];
        self.noRecomendInfo = [NSMutableArray array];
        
        int i = 0   ;
        for (NSDictionary *dict  in self.recommendInfo) {
            if (i<8) {
                [self.selectArr addObject:dict[@"title"]];
            }else {
                [self.noSelectArr addObject:dict[@"title"]];
                [self.noRecomendInfo addObject:dict];
            }
        }
        //保存数据表示已经登陆过了
        [[NSUserDefaults standardUserDefaults] setObject:@"第一次登陆" forKey:@"firstLogin"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    
        [[NSUserDefaults standardUserDefaults] setObject:self.recommendInfo forKey:@"recommendInfo"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        [[NSUserDefaults standardUserDefaults] setObject:self.noRecomendInfo forKey:@"noRecommendInfo"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }else {//如果不是第一次登陆则从本地读数据
       
        self.recommendInfo = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"recommendInfo"]];
        self.noRecomendInfo = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"noRecommendInfo"]];
        for (NSDictionary *dict in self.recommendInfo) {
            [self.selectArr addObject:dict[@"title"]];
        }
        for (NSDictionary *dict in self.noRecomendInfo) {
            [self.noSelectArr addObject:dict[@"title"]];
        }
        
    }
    
    // Do any additional setup after loading the view, typically from a nib.
    self.tabControl = [[TopTabControl alloc] initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, self.view.bounds.size.height-49)];
    self.tabControl.datasource = self;
    [self.tabControl reloadData];
    self.tabControl.showIndicatorView = YES;
    [self.view addSubview:self.tabControl];
    
    /*
     添加更多内容 按钮
     */
    [self createMoreMenuScrollView];
    [self createAddGroupBtn];
//
    
    [self createBgGrayView];
    [self createSearchButton];
}

- (void)createSearchButton {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
//    [button setTitle:@"侧边栏" forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"bar_btn_icon_search"] forState:UIControlStateNormal];
    button.frame = CGRectMake(kScreenWidth-40, 23, 40, 40);
    [button addTarget:self action:@selector(sideBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    button.userInteractionEnabled = YES;
    [self.view addSubview:button];
}

- (void)sideBtnClick:(UIButton *)button {
    YRSideViewController *sideViewController = [((AppDelegate*)[[UIApplication sharedApplication] delegate]) sideViewController ];
    [sideViewController showLeftViewController:YES  ];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self displayCustomTabBar];
}

- (void)createMoreMenuScrollView {
    self.moreMenuScrollView = [[[NSBundle mainBundle] loadNibNamed:@"MoreMenuScrollView" owner:self options:nil] lastObject];
    
    self.moreMenuScrollView.alpha = 0;
//    [self.moreMenuScrollView setContentSize:CGSizeMake(kScreenWidth, kMoreScrollViewHeight+50)];
    [self.view addSubview:self.moreMenuScrollView];
    [self createMenuCollectionView];
}

- (void)createMenuCollectionView {
    UICollectionViewFlowLayout *flowlayout1 = [[UICollectionViewFlowLayout alloc] init];
    flowlayout1.sectionInset = UIEdgeInsetsZero;
    flowlayout1.minimumInteritemSpacing = 3;
    flowlayout1.minimumLineSpacing = 5;
    flowlayout1.itemSize = CGSizeMake(70, 30);
    flowlayout1.scrollDirection = UICollectionViewScrollDirectionVertical;

    self.moreMenuScrollView.selectCollectionView.collectionViewLayout = flowlayout1;
    [self.moreMenuScrollView.selectCollectionView registerNib:[UINib nibWithNibName:@"SelectMenuCell" bundle:nil] forCellWithReuseIdentifier:kSelectCellId];
    
    self.moreMenuScrollView.selectCollectionView.delegate =self;
    self.moreMenuScrollView.selectCollectionView.dataSource =self;
    
    UICollectionViewFlowLayout *flowlayout2 = [[UICollectionViewFlowLayout alloc] init];
    flowlayout2.sectionInset = UIEdgeInsetsZero;
    flowlayout2.minimumInteritemSpacing = 2;
    flowlayout2.minimumLineSpacing = 5;
    flowlayout2.itemSize = CGSizeMake(70, 30);
    flowlayout2.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.moreMenuScrollView.noSelectCollectionView.collectionViewLayout = flowlayout2;
    [self.moreMenuScrollView.noSelectCollectionView registerNib:[UINib nibWithNibName:@"NoSelectMenuCell" bundle:nil] forCellWithReuseIdentifier:kNoSelectCellId];
    
    self.moreMenuScrollView.noSelectCollectionView.delegate =self;
    self.moreMenuScrollView.noSelectCollectionView.dataSource =self;

}

- (void)createBgGrayView {
    self.bgGrayView = [[BaseGrayView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight-20)];
    [[[UIApplication sharedApplication].delegate window] addSubview:self.bgGrayView];
    __weak typeof(self) mySelf = self;
    self.bgGrayView.myBlock = ^ {
        [UIView animateWithDuration:0.5 animations:^{
            [mySelf.moreMenuScrollView removeFromSuperview];
            mySelf.moreContentBtn.transform = CGAffineTransformRotate(mySelf.moreContentBtn.transform, M_PI);
        }];
    };
}

- (void)createAddGroupBtn {
    self.moreContentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.moreContentBtn setImage:[UIImage imageNamed:@"button_morecontent"] forState:UIControlStateNormal];
    self.moreContentBtn.frame = CGRectMake(kScreenWidth-67, 38, 20, 10);

    [self.moreContentBtn addTarget:self action:@selector(moreBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.moreContentBtn];
}

- (void)moreBtnClick:(UIButton *)button {
    if (self.bgGrayView.alpha == 0.5) {
        [UIView animateWithDuration:0.5 animations:^{
            
            button.transform = CGAffineTransformRotate(button.transform, M_PI);
            
            self.bgGrayView.alpha = 0;
            [self.moreMenuScrollView removeFromSuperview];
            
//            self.moreMenuScrollView.alpha = 1;
            
        }];
        return;
    }
    [UIView animateWithDuration:0.5 animations:^{
        
        button.transform = CGAffineTransformRotate(button.transform, M_PI);
        
        self.bgGrayView.alpha = 0.5;
        self.moreMenuScrollView.frame = CGRectMake(0, 64, kScreenWidth, kMoreScrollViewHeight);
        [[[UIApplication sharedApplication].delegate window] addSubview:self.moreMenuScrollView];
        
        self.moreMenuScrollView.alpha = 1;
        
    }];
    
}

//设置菜单的个数
- (NSInteger)TopTabMenuCount:(TopTabControl *)tabCtrl
{
    return self.recommendInfo.count;
}

- (CGFloat)TopTabHeight:(TopTabControl *)tabCtrl {
    return 44;
}

- (CGFloat)TopTabWidth:(TopTabControl *)tabCtrl {
    return 240;
}

- (TopTabMenuItem *)TopTabControl:(TopTabControl *)tabCtrl itemAtIndex:(NSUInteger)index {
    TopTabMenuItem *item = [[TopTabMenuItem alloc] initWithFrame:CGRectMake(0, 0, 60, 44)];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:self.recommendInfo[index][@"title"] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor customBlueColor] forState:UIControlStateSelected];
    button.frame = item.bounds;
    button.userInteractionEnabled = NO;
    
    [item addSubview:button];
    
    return item;
}

- (TopTabPage *)TopTabControl:(TopTabControl *)tabCtrl pageAtIndex:(NSUInteger)index {
    TopTabPage *page = [[TopTabPage alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-49-64)];
    page.backgroundColor = [UIColor greenColor];
    
    if ([self.recommendInfo[index][@"title"] isEqualToString:@"最新"] ) { //最新
        NewestRecommend *vc = [[NewestRecommend alloc] init];
        vc.info = self.recommendInfo[0];
        vc.view.frame = page.bounds;
        
//        page.vc = vc;
        [self addChildViewController:vc  ];
        [page addSubview:vc.view];
        vc.myPageJumpBlcok = ^(UIViewController *vc) {
            [self.navigationController pushViewController:vc animated:YES];
        };
        vc.myHiddeTabBarBlock = ^ (BOOL isHidden){
            NSArray *array = self.tabBarController.view.subviews;
            for (UIView *view in array) {
                if (view.tag == 100) {
                    view.hidden = isHidden;
                }
            }
        };
        vc.myJumpBlcok = ^(UIViewController *vc) {
            [self presentViewController:vc animated:YES completion:nil];
        };
        return page;
    }
    if ([self.recommendInfo[index][@"title"] isEqualToString:@"快报"]) {  //快报
        NewsflashRecommend *vc = [[NewsflashRecommend alloc] init];
        vc.info = self.recommendInfo[index];
        vc.view.frame = page.bounds;
        
        //        page.vc = vc;
        
        [self addChildViewController:vc  ];
        [page addSubview:vc.view];
        vc.myPageJumpBlcok = ^(UIViewController *vc) {
            [self.navigationController pushViewController:vc animated:YES];
        };
        
        vc.myHiddeTabBarBlock = ^ (BOOL isHidden){
            NSArray *array = self.tabBarController.view.subviews;
            for (UIView *view in array) {
                if (view.tag == 100) {
                    view.hidden = isHidden;
                }
            }
        };
        return page;
    }
    
    
    RecommendContent *vc = [[RecommendContent alloc] init];
    vc.info  = self.recommendInfo[index];
    
    vc.view.frame = page.bounds;
    vc.myPageJumpBlcok = ^(UIViewController *vc) {
        [self.navigationController pushViewController:vc animated:YES];
    };
    vc.myHiddeTabBarBlock = ^ (BOOL isHidden){
        NSArray *array = self.tabBarController.view.subviews;
        for (UIView *view in array) {
            if (view.tag == 100) {
                view.hidden = isHidden;
            }
        }
    };
    
    [self addChildViewController:vc  ];
    
    [page addSubview:vc.view];
    return page;
}

#pragma  mark - UICollectionViewDatasource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView == self.moreMenuScrollView.selectCollectionView) {
        return self.selectArr.count;
    }else {
        return self.noSelectArr.count;
    }
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.moreMenuScrollView.selectCollectionView == collectionView) {
        
        SelectMenuCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kSelectCellId forIndexPath:indexPath];
        if (indexPath.row == 0) {
            cell.contentLabel.backgroundColor = [UIColor clearColor];
        }else  {
            cell.contentLabel.backgroundColor = [UIColor whiteColor];
        }
        cell.contentLabel.text = self.selectArr[indexPath.row];
        return cell;
    }else {
        NoSelectMenuCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kNoSelectCellId forIndexPath:indexPath];
        cell.contentLabel.text = self.noSelectArr[indexPath.row];
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.moreMenuScrollView.selectCollectionView == collectionView) {
        if (indexPath.row == 0) {
            return;
        }
        NSString *str = self.selectArr[indexPath.row];
        
        [self.selectArr removeObject:str];
        [self.noSelectArr addObject:str];
            
        [self.moreMenuScrollView.selectCollectionView reloadData];
        [self.moreMenuScrollView.noSelectCollectionView reloadData];
       
        
        NSDictionary *dict = [self.recommendInfo objectAtIndex:indexPath.row];
 
        [self.recommendInfo  removeObjectAtIndex:indexPath.row];
        [self.noRecomendInfo addObject:dict];
        
        

        
    }else {
        NSString *str = self.noSelectArr[indexPath.row];
        [self.noSelectArr removeObject:str ];
        [self.selectArr addObject:str];
        [self.moreMenuScrollView.noSelectCollectionView reloadData];
        [self.moreMenuScrollView.selectCollectionView reloadData];
        
        NSDictionary *dict = self.noRecomendInfo[indexPath.row];
        [self.noRecomendInfo removeObject:dict];
        [self.recommendInfo addObject:dict];
    }
    [[NSUserDefaults standardUserDefaults] setObject:self.recommendInfo forKey:@"recommendInfo"];
    [[NSUserDefaults standardUserDefaults] setObject:self.noRecomendInfo forKey:@"noRecommendInfo"];
    
    [self.tabControl reloadData];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
